<template>
    <dbant-loading :loading="viewLoading">
        <el-container class="container">
            <el-header>
                <el-input placeholder="输入关键字进行过滤" v-model="groupFilterText" clearable>
                </el-input>
            </el-header>
            <el-main class="nopadding">
                <div class="query-tree-side-scroll">
                    <el-scrollbar>
                        <el-tree ref="group" class="menu" empty-text="未创建数据源连接" node-key="id" :data="tree.groupData"
                            :current-node-key="''" :highlight-current="true" :expand-on-click-node="false"
                            :default-expanded-keys="tree.defualtExpendedKeys" :filter-node-method="groupFilterNode"
                            :props="tree.defaultProps">
                            <template #default="{ node }">
                                <span @dblclick="dbClient(node)" class="custom-tree-node menus"
                                    @contextmenu="contextMenuClick(node, $event)">
                                    <el-icon :style="iconStyleObject(node)"><dbant-icon :icon="getIcon(node)" /></el-icon>
                                    <span> {{ node.label }}</span>
                                </span>
                            </template>
                        </el-tree>
                    </el-scrollbar>
                </div>
            </el-main>



        </el-container>


        <el-dialog v-model="pluginComponenDialogtVisible" :title="pluginComponentDialogInfo.title"
            v-if="pluginComponenDialogtVisible" custom-class="plugin-dialog"
            :width="pluginComponentDialogInfo.width ? pluginComponentDialogInfo.width : '400px'" append-to-body
            :show-close="false" :before-close="handleClose" destroy-on-close>
            <!-- <div :style="{height:pluginComponentDialogInfo.height?pluginComponentDialogInfo.height:'100%'}"> -->
            <component :is="pluginComponentDialogInfo.component" @closeDialog="handleClose"
                v-bind="pluginComponentDialogInfo.data"></component>
            <!-- </div> -->

        </el-dialog>
        <vue3-menus v-model:open="isOpen" :event="eventVal" :menus="menus" hasIcon>
            <template #icon="{ item: { activeIndex } }">{{ activeIndex }}</template>
            <template #label="{ item: { item } }">{{ item.label }}</template>
        </vue3-menus>
    </dbant-loading>
</template>

<script>
import { defineAsyncComponent, ref, nextTick } from "vue";
import { remove } from 'lodash'
import { WorkbeanchTab } from "@/components/WorkbeanchTab.js";
import {
    ElMessage, ElMessageBox, ElDialog
}
    from "element-plus";

export default {
    name: "QueryResource",
    props: {
    },

    data() {
        return {
            offset: 0.4,
            groupFilterText: "",
            tree: {
                groupData: [],
                defaultProps: {
                    id: "id",
                    children: "children",
                    label: "name",
                    isLeaf: "leaf",
                },
                defualtExpendedKeys: [],
                node: {},
            },
            search: {
                keyword: "",
            },
            viewLoading: true,
            rightMenuVisible: false,
            rightMenuComponent: null,
            rightMenu: ref(),
            isOpen: true,
            eventVal: {},
            menus: ref([]),
            currentNode: {},
            contextMenuComponent: null,
            contextMenuComponentData: null,
            pluginComponenDialogtVisible: ref(false),
            pluginComponentDialogInfo: ref({
                title: '信息',
                width: '300px',
                component: '',
                data: {

                }
            })
        };
    },
    watch: {
        groupFilterText(val) {
            this.$refs.group.filter(val);
        },
    },
    computed: {
        iconStyleObject: () => {
            return (node) => {
                if (node.data.type === "CONN") {
                    let color = node.childrenLoaded ? "#165EFF" : "#8a8a8a";
                    return `color:` + color + `;margin-right:2px`;
                }
                return `color:#165EFF;margin-right:2px`;
            };
        },
    },
    mounted() {
        this.$CONFIG.LOADED_CONN_IDS.length = 0;
        this.$API.connection.getTree().then((res) => {
            this.tree.groupData = res.data;
        }).finally(() => {
            this.viewLoading = false
        }
        );
        this.$bus.$on(this.$CONFIG.REFRESH_NODE, (node) => {
            this.refreshClient(node ? node : this.currentNode);
        });
        this.$bus.$on(this.$CONFIG.REFRESH_PARENT_NODE, (node) => {
            this.refreshClient(node ? node.parent ? node.parent : node : this.currentNode.parent
                ? this.currentNode.parent : this.currentNode);
        });
        this.$bus.$on(this.$CONFIG.DELETE_NODE_CHILDREN, (node) => {
            node.childrenLoaded = false;
            node.data.children = [];
            if (node.data.type === 'CONN') {
                remove(this.$CONFIG.LOADED_CONN_IDS, function (n) {
                    return n === node.data.properties.connId;
                })
                console.log("删除数据：" + this.$CONFIG.LOADED_CONN_IDS);
            }

        });
        this.$bus.$on(this.$CONFIG.REFRESH_NODE, (node) => {
            this.dbClient(node);
        });
        this.$bus.$on(
            this.$CONFIG.CONTEXT_MENU_EVENT_KEY,
            (data) => {
                console.log(data)
                let type = data.type;
                this.pluginComponentDialogInfo = {};
                this.pluginComponenDialogtVisible = false;
                if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_DIALOG)) {
                    this.pluginComponentDialogInfo = data;
                    this.pluginComponenDialogtVisible = true;
                }
                if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_TAGS_COM)) {
                    data.type = 'add'
                    this.$bus.$emit(this.$CONFIG.TAGS_EVENT_KEY, new WorkbeanchTab(data))
                }

                if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_TAGS_ROUTER)) {
                    this.contextMenuComponentData = data;
                    this.contextMenuComponent = component;
                }
                if ((type === this.$CONFIG.CONTEXT_MENU_TYPE_ROUTER)) {
                    this.contextMenuComponentData = data;
                    this.contextMenuComponent = component;
                }
            }
        );
    },
    methods: {
        handleClose() {
            this.pluginComponenDialogtVisible = false;
        },
        getIcon(node) {
            const pluginJs = this.$pluginService.getPlugin(node.data.properties.pluginId)
            if (!pluginJs) {
                return '#dbant-icon-' + node.data.type.toLowerCase();
            }
            const typeObj = pluginJs.resource[node.data.type.toLowerCase()];
            if (typeObj && typeObj.icon) {
                return pluginJs.resource[node.data.type.toLowerCase()].icon;
            }
            return node.data.type.toLowerCase();
        },
        contextMenuClick(node, event) {
            this.currentNode = node;
            const pluginJs = this.$pluginService.getPlugin(node.data.properties.pluginId)
            this.menus = [];
            const disabled = node && node.childrenLoaded;
            console.log(node)
            if (disabled) {
                this.menus.push({
                    label: "关闭",
                    click: () => {
                        this.$bus.$emit(this.$CONFIG.DELETE_NODE_CHILDREN, node)
                    },
                })

            } else {
                this.menus.push({
                    label: "打开",
                    click: () => {

                        if (node.data.leaf) {
                            this.nodeDataView(node)
                            return true;
                        }
                        this.$bus.$emit(this.$CONFIG.REFRESH_NODE, node)
                        return true;
                    },
                })
            }
            if (pluginJs && pluginJs.resource[
                node.data.type.toLowerCase()
            ]) {
                this.menus.push(...pluginJs.resource[
                    node.data.type.toLowerCase()
                ].contextMenu({ node: node }));
            }
            this.menus.push({
                label: "刷新",
                disabled: !disabled,
                dividedTop: true,
                click: () => {
                    this.refreshClient(node);
                },
            })
            this.isOpen = false;
            nextTick(() => {
                this.eventVal = event;
                this.isOpen = true;
            });
            event.preventDefault();
        },

        dbClient(node) {
            //判断如果已经加载过数据了，那么就不再进行加载数据
            if (
                !node.data ||
                !node.data.properties ||
                node.data.leaf ||
                node.childrenLoaded
            ) {
                if (node.data.leaf) {
                    this.nodeDataView(node)
                    return;
                }
                //未展开就进行展开
                if (!node.expanded) {
                    node.expanded = true;
                } else {
                    node.expanded = false;
                }

                return;
            }

            //开启加载如表
            node.loading = true;
            const pluginJs = this.$pluginService.getPlugin(node.data.properties.pluginId)
            if (!pluginJs) {
                node.data.children = [];
                node.loading = false;
                return;
            }

            const resource = pluginJs.resource[
                node.data.type.toLowerCase()
            ];

            if (resource) {
                resource.metadata({ node: node })
                    .then(res => {
                        //进行数据转换
                        node.data.children = res;
                        //设置已经加载过的标识
                        node.childrenLoaded = true;
                        this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId)
                        //展开
                        node.expanded = true;
                    })
                    .finally(() => {
                        //关闭加载图标
                        node.loading = false;
                    });
                // node.data.children = dataConvert.defaultValue();
                // //设置已经加载过的标识
                // node.childrenLoaded = true;
                // this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId)
                // //展开
                // node.expanded = true;
                // //关闭加载图标
                // node.loading = false;
                return;
            }
            // const executeParams = { script: dataConvert.buildScript(), noPage: true };

            // const params = Object.assign({
            //     executeParams: executeParams
            // }, node.data.properties);

            // this.$API.sqlDatabase.executeSqlScript(params)
            //     .then((res) => {
            //         //进行数据转换
            //         node.data.children = dataConvert.covert(res.data[0]);
            //         //设置已经加载过的标识
            //         node.childrenLoaded = true;
            //         this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId)
            //         //展开
            //         node.expanded = true;
            //     }).finally(() => {
            //         //关闭加载图标
            //         node.loading = false;
            //     });



            // data.children.push(newChild);
            //   this.$refs.group.updateKeyChildren(node.id, res.data);
            //   this.tree.defualtExpendedKeys = [node.id];
            //   this.$refs.group.setCurrentKey(node.id);
            // });
        },
        refreshClient(node) {
            //判断如果已经加载过数据了，那么就不再进行加载数据
            if (
                !node.data ||
                !node.data.properties ||
                node.data.leaf
            ) {

                return;
            }
            //开启加载如表
            node.loading = true;
            const pluginJs = this.$pluginService.getPlugin(node.data.properties.pluginId)
            if (!pluginJs) {
                this.$message.error("插件未安装，无法加载数据");
                node.data.children = [];
                node.loading = false;
                return;
            }

            const resource = pluginJs.resource[
                node.data.type.toLowerCase()
            ];


            if (resource) {
                resource.metadata({ node: node })
                    .then(data => {

                        let arr = node.data.children.filter((item, index) => data.some(newItem =>
                            newItem.id === item.id
                        )
                        );
                        node.data.children = [...arr, ...data.filter(item => !arr.some(newItem => newItem.id == item.id))];
                        //设置已经加载过的标识
                        node.childrenLoaded = true;
                        this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId);
                        //展开
                        node.expanded = true;
                    })
                    .finally(() => {
                        //关闭加载图标
                        node.loading = false;
                    });
                // node.data.children = dataConvert.defaultValue();
                // //设置已经加载过的标识
                // node.childrenLoaded = true;
                // this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId)
                // //展开
                // node.expanded = true;
                // //关闭加载图标
                // node.loading = false;
                return;
            }


            // if (dataConvert.defaultValue) {
            //     node.data.children = dataConvert.defaultValue();
            //     //设置已经加载过的标识
            //     node.childrenLoaded = true;
            //     this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId)
            //     console.log("添加数据：" + this.$CONFIG.LOADED_CONN_IDS);
            //     //展开
            //     node.expanded = true;
            //     //关闭加载图标
            //     node.loading = false;
            //     return;
            // }
            // const executeParams = { script: dataConvert.buildScript(), noPage: true };
            // const params = Object.assign({
            //     executeParams: executeParams
            // }, node.data.properties);
            // this.$API.sqlDatabase.executeSqlScript(params)
            //     .then((res) => {
            //         //没有数据就设置空数据
            //         if (!res.data) {
            //             this.$set(node.data, "children", []);
            //         }
            //         let data = dataConvert.covert(res.data[0]);
            //         let arr = node.data.children.filter((item, index) => data.some(newItem =>
            //             newItem.id === item.id
            //         )
            //         );
            //         node.data.children = [...arr, ...data.filter(item => !arr.some(newItem => newItem.id == item.id))];
            //         //设置已经加载过的标识
            //         node.childrenLoaded = true;
            //         this.$CONFIG.LOADED_CONN_IDS.push(node.data.properties.connId);
            //         //展开
            //         node.expanded = true;
            //     })
            //     .finally(() => {
            //         //关闭加载图标
            //         node.loading = false;
            //     });
            // data.children.push(newChild);
            //   this.$refs.group.updateKeyChildren(node.id, res.data);
            //   this.tree.defualtExpendedKeys = [node.id];
            //   this.$refs.group.setCurrentKey(node.id);
            // });
        },

        nodeDataView(node) {
            const pluginJs = this.$pluginService.getPlugin(node.data.properties.pluginId)
            if (!pluginJs) {
                this.$message.error("插件未安装，无法加载数据");
                node.data.children = [];
                node.loading = false;
                return;
            }
            const dataView = pluginJs.resource[
                node.data.type.toLowerCase()
            ].dataView({ node: node });
            const executeParams = { script: dataView.buildScript(node) };
            const params = Object.assign({
                executeParams: executeParams
            }, node.data.properties);
            this.$API.sqlDatabase.executeSqlScript(params)
                .then((res) => {
                    //没有数据就设置空数据
                    if (!res.data) {
                        return;
                    }
                    if (!res.data[0].success) {
                        opt.message.error(res.message);
                        return;
                    }

                    this.$bus.$emit(this.$CONFIG.CONTEXT_MENU_EVENT_KEY, dataView.display(res.data[0]))
                })
                .finally(() => {
                    //关闭加载图标
                    node.loading = false;
                });

        },
        //树过滤
        groupFilterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        handleCommand(command) {
            if (command == "closeConn") {
                this.tree.node.childrenLoaded = false;
                this.tree.node.data.children = [];
            }
            if (command == "openConn") {
                this.dbClient(this.tree.node);
            }
        },

        visibleChange(visible) {
            if (!visible) {
            }
        },
        //树点击事件
        groupClick(data) {
            var params = {
                groupId: data.id,
            };
            this.$refs.table.reload(params);
        },
        //搜索
        upsearch() {
            this.$refs.table.upData(this.search);
        },
    },
};
</script>

<style lang="scss"  >
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
    height: 36px;
    padding-right: 10px;
}

.container {
    /*双击文字、input等，出现的蓝色底色，如何去除*/
    -moz-user-select: none;
    /*火狐*/
    -webkit-user-select: none;
    /*webkit浏览器*/
    -ms-user-select: none;
    /*IE10*/
    /*-khtml-user-select:none;!*早期浏览器*!*/
    user-select: none;
}

.query-tree-side-scroll {
    overflow: auto;
    overflow-x: hidden;
    height: 100%;
    flex: 1;
}

.plugin-dialog {
    // --el-dialog-padding-primary: 10px;

    // :deep(.el-dialog__body) {
    //     padding: 0px 10px 10px 10px;
    //     display: flex;
    //     flex-direction: column;


    //     :depp(.dialog-footer){
    //         display: flex;
    //         flex-direction: column-reverse;
    //     }
    // }
}
</style>
